import { useState, useRef, useEffect } from 'react'

// eslint-disable-next-line no-unused-vars
import style from './todolist.module.css'
import './todolist.scss'

function TodoList() {
  const inputRef = useRef(null)
  const [comments, setComments] = useState([])

  // 挂载
  useEffect(() => {
    inputRef.current.focus()
  }, [])

  // 添加评论
  const addComment = () => {
    let content = inputRef.current.value.trim()
    if (!content) {
      alert('内容不能为空')
      inputRef.current.value = ''
      inputRef.current.focus()
      return
    }
    setComments([{ id: Date.now(), content }, ...comments])

    inputRef.current.value = ''
  }

  // 删除评论
  const del = (item) => {
    if (!confirm('确认删除吗')) {
      return
    }

    const newComments = comments.filter((content) => item.id !== content.id)
    setComments(newComments)
  }

  // 回车键发布评论
  const submit = (e) => {
    if (e.keyCode === 13) {
      addComment()
    }
  }

  return (
    <>
      <div className="container">
        <div>
          <input
            type="text"
            name="keyword"
            autoComplete="on"
            placeholder="输入"
            ref={inputRef}
            onKeyUp={(e) => {
              submit(e)
            }}
          />
          <button onClick={addComment}>发布</button>
        </div>
        <ul>
          {comments.map((item) => (
            <li key={item.id}>
              <span>{item.content}</span>
              <a
                href="#"
                onClick={() => {
                  del(item)
                }}
              >
                删除
              </a>
            </li>
          ))}
        </ul>
      </div>
    </>
  )
}

export default TodoList
